package codeine.servlets;

import java.io.PrintWriter;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import codeine.configuration.ConfigurationManager;
import codeine.configuration.Links;
import codeine.jsons.project.ProjectJson;
import codeine.servlet.AbstractServlet;
import codeine.servlet.HtmlHeaderWriter;
import codeine.servlet.PermissionsManager;

import com.google.inject.Inject;

public class ProjectsDashboardServlet extends AbstractServlet
{
	private static final Logger log = Logger.getLogger(DashboardServlet.class);
	private static final long serialVersionUID = 1L;
	
	@Inject private HtmlHeaderWriter htmlHeaderWriter;
	@Inject private ConfigurationManager configurationManager;
	@Inject private Links links;
	@Inject private PermissionsManager permissionsManager;

	@Override
	protected void myGet(HttpServletRequest request, HttpServletResponse response) {
		log.debug("dashboard request");
		PrintWriter writer = getWriter(response);
		htmlHeaderWriter.writeHeader(request, response, null, "projects");
		for (ProjectJson project : getSortedProjects())
		{
			if (permissionsManager.isModifiable(project.name(), request)){
				String line = "            <alert><div class=\"alertbar\"><ul>";
				String projectLink = links.getProjectLink(project);
				line += "<li><a class=\"" + "nameg" + "\" href=\"" + projectLink+"\">" + project.name() + "</a></li>";
				line += "</ul><br style=\"clear:left\"/></div></alert>";
				writer.println(line);
			}
		}
		htmlHeaderWriter.writeFooter(response);
	}

	private List<ProjectJson> getSortedProjects() {
		List<ProjectJson> configuredProjects = configurationManager.getConfiguredProjects();
		Comparator<ProjectJson> c = new Comparator<ProjectJson>() {
			@Override
			public int compare(ProjectJson o1, ProjectJson o2) {
				return o1.name().compareTo(o2.name());
			}
		};
		Collections.sort(configuredProjects, c);
		return configuredProjects;
	}
}
